package org.koin.test.mock;

import org.koin.core.Koin;
import org.koin.core.annotation.KoinInternalApi;
import org.koin.core.error.DefinitionOverrideException;
import org.koin.core.qualifier.Qualifier;
import org.koin.core.scope.Scope;
import org.koin.test.KoinTest;
import java.util.List;

public class DeclareMock {

    public static <T> T declareMock(KoinTest koinTest,
                                    Class<T> clazz,
                                    Qualifier qualifier,
                                    List<Class> secondaryTypes,
                                    StubFunction<T> stubbing) {
        Koin koin = koinTest.getKoin();
        return declareMock(koin, clazz, qualifier, secondaryTypes, stubbing);
    }

    @KoinInternalApi
    public static <T> T declareMock(Koin koin,
                                    Class<T> clazz,
                                    Qualifier qualifier,
                                    List<Class> secondaryTypes,
                                    StubFunction<T> stubbing) {
        Scope scope = koin.getScopeRegistry().getRootScope();
        return declareMock(scope, clazz, qualifier, secondaryTypes, stubbing);
    }

    public static <T> T declareMock(Scope scope, Class<T> clazz,
                                    Qualifier qualifier,
                                    List<Class> secondaryTypes,
                                    StubFunction<T> stubbing) {
        T mock = (T) MockProvider.INSTANCE().makeMock();
        try {
            scope.declare(clazz, mock, qualifier, secondaryTypes, true);
            stubbing.invoke(mock);
        } catch (DefinitionOverrideException e) {
            e.printStackTrace();
        }
        return mock;
    }
}
